<template>
  <div class="blog-comment-container">
    <MessageArea title="评论列表" :subTitle="`(${data.total})`" :list="data.rows" :isListLoading="isLoading"
      @submit="handleSubmit" />
    <noMore v-if="show" />
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import fetchData from "@/mixins/fetchData.js";
import { getComments, postComment } from "@/api/blog.js";
import noMore from '@/components/noMore';
export default {
  mixins: [fetchData({ total: 0, rows: [] })],
  components: {
    MessageArea,
    noMore
  },
  data() {
    return {
      page: 1,
      limit: 10,
      show: false
    };
  },
  created() {
    // 监听主区域
    this.$bus.$on('mainScroll', this.handleScroll);
  },
  destroyed() {
    // 取消监听
    this.$bus.$off('mainScroll', this.handleScroll);
  },
  methods: {
    // 处理滚动事件
    handleScroll(dom) {
      if (this.isLoading || !dom) {
        // 正在加载，什么也不干
        return;
      }
      const range = 100;
      // 差值 = 元素滚动条高度
      const dec = Math.abs(dom.scrollTop + dom.clientHeight - dom.scrollHeight);
      if (dec < range) {
        this.fetchNext();
      }
    },
    // 加载下一页评论
    async fetchNext() {
      if (!this.hasMore) {
        // 没有更多数据就不在继续请求
        // 同时显示没有更多数据了
        this.show = true;
        return;
      }
      this.isLoading = true;
      this.page++;
      const resp = await this.fetchData();
      this.total = resp.total;
      this.data.rows = this.data.rows.concat(resp.rows);
      this.isLoading = false;
    },
    async fetchData() {
      return await getComments(this.$route.params.id, this.page, this.limit);
    },
    async handleSubmit(formData, callback) {
      const resp = await postComment({
        blogId: this.$route.params.id,
        ...formData,
      });
      this.data.rows.unshift(resp);
      this.data.total++;
      callback("评论成功"); // 告诉子组件，我这边处理完了，你继续
    },
  },
  computed: {
    // 是否还有更多的数据
    hasMore() {
      const d = this.data.rows.length < this.data.total
      return d;
    }
  },

};
</script>

<style scoped lang="less">
.blog-comment-container {
  margin: 30px 0;
  position: relative;
}
</style>
